// 全局配置
const CONFIG = {
    API_BASE_URL: '/api/v1',
    STORAGE_KEYS: {
        TOKEN: 'auth_token',
        THEME: 'theme_preference',
        USER: 'user_info'
    }
};

// 工具函数
class Utils {
    // 本地存储操作
    static setStorage(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error('Storage set error:', error);
        }
    }

    static getStorage(key) {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : null;
        } catch (error) {
            console.error('Storage get error:', error);
            return null;
        }
    }

    static removeStorage(key) {
        try {
            localStorage.removeItem(key);
        } catch (error) {
            console.error('Storage remove error:', error);
        }
    }

    // HTTP 请求封装
    static async request(url, options = {}) {
        const token = Utils.getStorage(CONFIG.STORAGE_KEYS.TOKEN);
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                ...(token && { 'Authorization': `Bearer ${token}` })
            }
        };

        const config = {
            ...defaultOptions,
            ...options,
            headers: {
                ...defaultOptions.headers,
                ...options.headers
            }
        };

        try {
            const response = await fetch(`${CONFIG.API_BASE_URL}${url}`, config);
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || `HTTP error! status: ${response.status}`);
            }
            
            return data;
        } catch (error) {
            console.error('Request error:', error);
            throw error;
        }
    }

    // 显示通知
    static showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; font-size: 1.2rem; cursor: pointer;">&times;</button>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => notification.classList.add('show'), 100);
        
        // 自动移除
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    // 格式化日期
    static formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            const hours = Math.floor(diff / (1000 * 60 * 60));
            if (hours === 0) {
                const minutes = Math.floor(diff / (1000 * 60));
                return minutes <= 1 ? '刚刚' : `${minutes}分钟前`;
            }
            return `${hours}小时前`;
        } else if (days === 1) {
            return '昨天';
        } else if (days < 7) {
            return `${days}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    }
}

// 主题管理
class ThemeManager {
    constructor() {
        this.currentTheme = Utils.getStorage(CONFIG.STORAGE_KEYS.THEME) || 'light';
        this.init();
    }

    init() {
        this.applyTheme(this.currentTheme);
        this.bindEvents();
    }

    bindEvents() {
        const themeToggle = document.querySelector('.theme-toggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', () => this.toggleTheme());
        }
    }

    toggleTheme() {
        this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        this.applyTheme(this.currentTheme);
        Utils.setStorage(CONFIG.STORAGE_KEYS.THEME, this.currentTheme);
    }

    applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        const themeIcon = document.querySelector('.theme-toggle i');
        if (themeIcon) {
            themeIcon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
        }
    }
}

// 模态框管理
class ModalManager {
    static show(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
    }

    static hide(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    }

    static init() {
        // 绑定关闭按钮事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-close')) {
                const modal = e.target.closest('.modal');
                if (modal) {
                    ModalManager.hide(modal.id);
                }
            }
            
            // 点击背景关闭
            if (e.target.classList.contains('modal')) {
                ModalManager.hide(e.target.id);
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                const openModal = document.querySelector('.modal.show');
                if (openModal) {
                    ModalManager.hide(openModal.id);
                }
            }
        });
    }
}

// 认证管理
class AuthManager {
    constructor() {
        this.currentUser = Utils.getStorage(CONFIG.STORAGE_KEYS.USER);
        this.init();
    }

    init() {
        this.updateUI();
        this.bindEvents();
    }

    bindEvents() {
        // 登录按钮
        const loginBtn = document.querySelector('.login-btn');
        if (loginBtn) {
            loginBtn.addEventListener('click', () => {
                if (this.currentUser) {
                    this.logout();
                } else {
                    ModalManager.show('loginModal');
                }
            });
        }

        // 登录表单
        const loginForm = document.querySelector('.login-form');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => this.handleLogin(e));
        }
    }

    async handleLogin(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const username = e.target.querySelector('input[type="text"]').value;
        const password = e.target.querySelector('input[type="password"]').value;
        
        if (!username || !password) {
            Utils.showNotification('请填写用户名和密码', 'error');
            return;
        }

        try {
            const submitBtn = e.target.querySelector('.submit-btn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading"></span> 登录中...';

            const response = await Utils.request('/users/login', {
                method: 'POST',
                body: JSON.stringify({ username, password })
            });

            Utils.setStorage(CONFIG.STORAGE_KEYS.TOKEN, response.token);
            Utils.setStorage(CONFIG.STORAGE_KEYS.USER, response.user);
            
            this.currentUser = response.user;
            this.updateUI();
            
            ModalManager.hide('loginModal');
            Utils.showNotification('登录成功', 'success');
            
            // 重置表单
            e.target.reset();
            
        } catch (error) {
            Utils.showNotification(error.message || '登录失败', 'error');
        } finally {
            const submitBtn = e.target.querySelector('.submit-btn');
            submitBtn.disabled = false;
            submitBtn.innerHTML = '登录';
        }
    }

    logout() {
        Utils.removeStorage(CONFIG.STORAGE_KEYS.TOKEN);
        Utils.removeStorage(CONFIG.STORAGE_KEYS.USER);
        this.currentUser = null;
        this.updateUI();
        Utils.showNotification('已退出登录', 'info');
    }

    updateUI() {
        const loginBtn = document.querySelector('.login-btn');
        if (loginBtn) {
            if (this.currentUser) {
                loginBtn.textContent = this.currentUser.nickname || this.currentUser.username;
                loginBtn.classList.add('logged-in');
            } else {
                loginBtn.textContent = '登录';
                loginBtn.classList.remove('logged-in');
            }
        }
    }
}

// 文章管理
class PostManager {
    constructor() {
        this.currentPage = 1;
        this.currentCategory = '';
        this.searchQuery = '';
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadPosts();
    }

    bindEvents() {
        // 搜索功能
        const searchForm = document.querySelector('.search-box');
        if (searchForm) {
            searchForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleSearch();
            });
        }

        const searchInput = document.querySelector('.search-input');
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.handleSearch();
                }
            });
        }

        // 分类筛选
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('category-item')) {
                e.preventDefault();
                this.handleCategoryFilter(e.target);
            }
            
            if (e.target.classList.contains('read-more-btn')) {
                this.handleReadMore(e.target);
            }
        });
    }

    handleSearch() {
        const searchInput = document.querySelector('.search-input');
        this.searchQuery = searchInput.value.trim();
        this.currentPage = 1;
        this.loadPosts();
    }

    handleCategoryFilter(categoryElement) {
        // 更新活跃状态
        document.querySelectorAll('.category-item').forEach(item => {
            item.classList.remove('active');
        });
        categoryElement.classList.add('active');
        
        this.currentCategory = categoryElement.textContent === '全部' ? '' : categoryElement.textContent;
        this.currentPage = 1;
        this.loadPosts();
    }

    handleReadMore(button) {
        const postCard = button.closest('.post-card');
        const postId = postCard.dataset.postId;
        if (postId) {
            // 这里可以跳转到文章详情页
            window.location.href = `/post/${postId}`;
        }
    }

    async loadPosts() {
        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                limit: 10,
                ...(this.currentCategory && { category: this.currentCategory }),
                ...(this.searchQuery && { search: this.searchQuery })
            });

            const response = await Utils.request(`/posts?${params}`);
            this.renderPosts(response.posts || []);
            this.renderPagination(response.pagination || {});
            
        } catch (error) {
            console.error('Load posts error:', error);
            Utils.showNotification('加载文章失败', 'error');
        }
    }

    renderPosts(posts) {
        const container = document.querySelector('.posts-container');
        if (!container) return;

        if (posts.length === 0) {
            container.innerHTML = `
                <div class="no-posts">
                    <p>暂无文章</p>
                </div>
            `;
            return;
        }

        container.innerHTML = posts.map(post => `
            <div class="post-card" data-post-id="${post.ID}" onclick="window.location.href='post.html?id=${post.ID}'" style="cursor: pointer;">
                <div class="post-header">
                    <h2 class="post-title">${post.Title}</h2>
                    <div class="post-meta">
                        <span class="author"><i class="fas fa-user"></i> ${post.User?.nickname || post.User?.username || '匿名'}</span>
                        <span class="date"><i class="fas fa-calendar"></i> ${Utils.formatDate(post.CreatedAt)}</span>
                        <span class="category"><i class="fas fa-tag"></i> ${post.Category?.Name || '未分类'}</span>
                    </div>
                </div>
                <div class="post-content">
                    <p>${post.Summary || post.Content.substring(0, 200) + '...'}</p>
                </div>
                <div class="post-footer">
                    <div class="post-stats">
                        <span><i class="fas fa-eye"></i> ${post.ViewCount || 0}</span>
                        <span><i class="fas fa-heart"></i> ${post.LikeCount || 0}</span>
                        <span><i class="fas fa-comment"></i> ${post.CommentCount || 0}</span>
                    </div>
                    <button class="read-more-btn" onclick="event.stopPropagation(); window.location.href='post.html?id=${post.ID}'">阅读更多</button>
                </div>
            </div>
        `).join('');
    }

    renderPagination(pagination) {
        const container = document.querySelector('.pagination');
        if (!container || !pagination.total_pages) return;

        const { current_page, total_pages } = pagination;
        let paginationHTML = '';

        // 上一页
        paginationHTML += `
            <button class="page-btn" ${current_page <= 1 ? 'disabled' : ''} onclick="postManager.goToPage(${current_page - 1})">
                <i class="fas fa-chevron-left"></i>
            </button>
        `;

        // 页码
        for (let i = Math.max(1, current_page - 2); i <= Math.min(total_pages, current_page + 2); i++) {
            paginationHTML += `
                <button class="page-btn ${i === current_page ? 'active' : ''}" onclick="postManager.goToPage(${i})">
                    ${i}
                </button>
            `;
        }

        // 下一页
        paginationHTML += `
            <button class="page-btn" ${current_page >= total_pages ? 'disabled' : ''} onclick="postManager.goToPage(${current_page + 1})">
                <i class="fas fa-chevron-right"></i>
            </button>
        `;

        container.innerHTML = paginationHTML;
    }

    goToPage(page) {
        this.currentPage = page;
        this.loadPosts();
    }
}

// 应用初始化
class App {
    constructor() {
        this.themeManager = new ThemeManager();
        this.authManager = new AuthManager();
        this.postManager = new PostManager();
        this.init();
    }

    init() {
        ModalManager.init();
        this.bindGlobalEvents();
        console.log('AwesomeProject 前端应用已启动');
    }

    bindGlobalEvents() {
        // 平滑滚动
        document.addEventListener('click', (e) => {
            if (e.target.matches('a[href^="#"]')) {
                e.preventDefault();
                const target = document.querySelector(e.target.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            }
        });

        // 返回顶部
        window.addEventListener('scroll', () => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const backToTop = document.querySelector('.back-to-top');
            if (backToTop) {
                backToTop.style.display = scrollTop > 300 ? 'block' : 'none';
            }
        });
    }
}

// 全局变量
let app, postManager;

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    app = new App();
    postManager = app.postManager;
});

// 导出到全局作用域（用于内联事件处理）
window.ModalManager = ModalManager;
window.Utils = Utils;